<?php

declare(strict_types=1);

namespace app\shop\controller\admin\commission;

use sheep\controller\Backend;
use app\shop\model\commission\Level as LevelModel;
use sheep\controller\traits\Crud;
use think\Request;
use think\Response;
use think\facade\Db;

class Level extends Backend
{
    use Crud;
    protected $model = null;

    public function initialize()
    {
        $this->model = new LevelModel();
    }

    /**
     * 查看
     *
     * @return Response
     */
    public function list(Request $request): Response
    {
        $defaultLevel = $this->model->find(1);
        if (!$defaultLevel) {
            $this->model->save([
                'name' => '默认等级',
                'level' => 1,
                'commission_rules' => [
                    'commission_1' => '0.00',
                    'commission_2' => '0.00',
                    'commission_3' => '0.00'
                ]
            ]);
        }
        $list = $this->model->sheepFilter()->select();

        return success('全部等级', $list);
    }

    /**
     * 编辑
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit(Request $request, $id)
    {
        $params = $request->only(['level', 'name', 'image', 'commission_rules', 'upgrade_type', 'upgrade_rules']);

        $result = Db::transaction(function () use ($id, $params) {

            $this->svalidate($params);

            $data = $this->model->findOrFail($id);

            return $data->save($params);
        });

        if ($result) {
            return success('更新成功', $result);
        } else {
            return error('更新失败');
        }
    }

    /**
     * 详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $detail = $this->model->findOrFail($id);
        return success('等级详情', $detail);
    }

    // 选择分销商等级
    public function select()
    {
        $data = $this->model->sheepFilter()->field('level, name, image, commission_rules')->select();
        return success('选择等级', $data);
    }
}
